import 'dart:async';

import 'dart:io';

import 'package:audio_session/audio_session.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:flutter_sound_platform_interface/flutter_sound_recorder_platform_interface.dart';
import 'package:get/get.dart';

import 'package:namewava/utils/jc_image_path.dart';
import 'package:namewava/utils/jc_screenutil_info.dart';
import 'package:namewava/utils/jc_text_style.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:svgaplayer_flutter/player.dart';
import 'package:path_provider/path_provider.dart';

class JcRecord extends StatefulWidget {
  const JcRecord({super.key, required this.recorderDismissEvents});
  final Function recorderDismissEvents;

  @override
  State<JcRecord> createState() => _JcRecordState();
}

class _JcRecordState extends State<JcRecord> {
  RxString soundIcon = JcImagePath.jcWavaSoundIcon.obs;
  RxString mkf = JcImagePath.jcWavaSoundNormalIcon.obs;

  final RxBool _isStartRecorder = false.obs;
  final RxBool _isEffective = true.obs;

  double effectiveHeight = 258.h;

  ///是否授权麦克风权限
  bool _isAuthority = false;

  FlutterSoundRecorder? _soundRecorder = FlutterSoundRecorder();

  bool _isInitRecorder = false;
  String _recorderPath = '';
  int _recorderTime = 0;
  Timer? _recorderTimer;
  ////初始化录音
  _initRecorder({bool isStarRecord = false}) async {
    await _soundRecorder!.openRecorder();

    final session = await AudioSession.instance;
    await session.configure(AudioSessionConfiguration(
      avAudioSessionRouteSharingPolicy:
          AVAudioSessionRouteSharingPolicy.defaultPolicy,
      androidWillPauseWhenDucked: true,
      avAudioSessionCategoryOptions:
          AVAudioSessionCategoryOptions.allowBluetooth |
              AVAudioSessionCategoryOptions.defaultToSpeaker,
      avAudioSessionCategory: AVAudioSessionCategory.playAndRecord,
      androidAudioAttributes: const AndroidAudioAttributes(
        contentType: AndroidAudioContentType.speech,
        flags: AndroidAudioFlags.none,
        usage: AndroidAudioUsage.voiceCommunication,
      ),
      avAudioSessionMode: AVAudioSessionMode.spokenAudio,
      avAudioSessionSetActiveOptions: AVAudioSessionSetActiveOptions.none,
      androidAudioFocusGainType: AndroidAudioFocusGainType.gain,
    ));

    _isInitRecorder = true;
    if (isStarRecord) {
      _starRecorder();
    }
  }

  ///开始录音
  _starRecorder() async {
    _isStartRecorder.value = true;
    _isEffective.value = true;
    mkf.value = JcImagePath.jcWavaSoundSelectIcon;
    soundIcon.value = JcImagePath.jcWavaSoundluyin;
    _recorderTimer ??= Timer.periodic(const Duration(seconds: 1), (timer) {
      _recorderTime++;
    });

    Directory tempDir = await getTemporaryDirectory();
    var time = DateTime.now().millisecondsSinceEpoch ~/ 1000;
    _recorderPath = '${tempDir.path}/$time${ext[Codec.aacADTS.index]}';
    _soundRecorder!
        .startRecorder(
          toFile: _recorderPath,
          codec: Codec.aacADTS,
          audioSource: AudioSource.microphone,
        )
        .then((value) {});
  }

  _stopRecorder() async {
    await _soundRecorder?.stopRecorder().then((value) {
      print('录音结束：$value  录音时长：$_recorderTime');

      _recorderTimer?.cancel();
      _recorderTimer = null;
      _isStartRecorder.value = false;
      if (_isEffective.value) {
        Get.back();
        widget.recorderDismissEvents(_recorderTime, _recorderPath);
      } else {
        _recorderTime = 0;
        print('无效tap区域,');
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    _soundRecorder?.closeRecorder();
    _soundRecorder = null;
  }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      _isAuthority = await requestPermission();
      _initRecorder();
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: Container(
        height: JcScreenutilInfo.screenHeight,
        width: JcScreenutilInfo.screenWidth,
        color: Colors.transparent,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            Obx(() {
              if (_isStartRecorder.value) {
                return Obx(() {
                  return Text(
                    _isEffective.value ? 'Release Send' : 'Release Cancel',
                    style: JcTextStyle.octoberDevanagariMediumTextStyle(
                        16.sp, _isEffective.value ? Colors.white : Colors.red),
                  );
                });
              } else {
                return SizedBox(
                  height: 10.h,
                );
              }
            }),
            SizedBox(height: 15.h),
            GestureDetector(
              child: Container(
                // margin: EdgeInsets.only(left: 30.w, right: 30.w),
                width: JcScreenutilInfo.screenWidth,
                height: 258.h,

                decoration: const BoxDecoration(
                    image: DecorationImage(
                        image: AssetImage(JcImagePath.jcWavaSoundBg),
                        fit: BoxFit.fill)),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Obx(() {
                      if (soundIcon.value.contains('png')) {
                        return Image.asset(
                          soundIcon.value,
                          width: 110.w,
                          height: 50.h,
                        );
                      } else {
                        return SizedBox(
                          height: 50.h,
                          width: 110.w,
                          child: SVGASimpleImage(
                            assetsName: soundIcon.value,
                          ),
                        );
                      }
                    }),
                    SizedBox(
                      height: 30.h,
                    ),
                    Obx(() {
                      return GestureDetector(
                        child: Image.asset(mkf.value),
                        onLongPressStart: (details) async {
                          print('onLongPressStart');
                          if (!_isAuthority) {
                            _isAuthority = await requestPermission();
                            if (_isAuthority) {
                              if (_isInitRecorder) {
                                _starRecorder();
                              } else {
                                _initRecorder(isStarRecord: true);
                              }
                            } else {
                              EasyLoading.showError(
                                  'Your microphone permission has been denied.');
                            }
                          } else {
                            if (_isInitRecorder) {
                              _starRecorder();
                            } else {
                              _initRecorder(isStarRecord: true);
                            }
                          }
                        },
                        onLongPressMoveUpdate: (details) async {
                          if (_isAuthority) {
                            double dy = details.globalPosition.dy;
                            bool isEf = false;
                            // print(dy);
                            if (dy >=
                                JcScreenutilInfo.screenHeight -
                                    effectiveHeight) {
                              isEf = true;
                            } else {
                              isEf = false;
                            }
                            print(isEf);
                            if (_isEffective.value == isEf) {
                            } else {
                              _isEffective.value = isEf;
                            }
                          }
                        },
                        onLongPressEnd: (r) {
                          if (_isAuthority) {
                            _stopRecorder();
                            mkf.value = JcImagePath.jcWavaSoundNormalIcon;
                            soundIcon.value = JcImagePath.jcWavaSoundIcon;
                          }
                        },
                      );
                    })
                  ],
                ),
              ),
              onTap: () {},
            )
          ],
        ),
      ),
      onTap: () {
        Get.back();
      },
    );
  }

  Future<bool> requestPermission() async {
    var status = await Permission.microphone.status;

    if (status == PermissionStatus.granted) {
      return true;
    } else {
      status = await Permission.microphone.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        return false;
      }
    }
  }
}
